//
//  DiscoverViewController.m
//  Read History
//
//  Created by Jam on 16/9/1.
//  Copyright © 2016年 Jam. All rights reserved.
//

#import "DiscoverViewController.h"
#import "DiscoverCell.h"
#import "NewsListController.h"
#import "ChannelAddViewController.h"

@interface DiscoverViewController ()<UITableViewDelegate,UITableViewDataSource,DiscoverDelegate>
{
    __weak IBOutlet UITableView *dataTable;
    __weak IBOutlet UILabel *lineLab;
    __weak IBOutlet UIButton *pressBtn;
    __weak IBOutlet UIView *selectView;
    NSMutableArray *dataList;
    NSMutableArray *cateList;
    NSInteger currentIndex;
}

@end

@implementation DiscoverViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    dataList = [NSMutableArray array];
    cateList = [NSMutableArray array];
    self.navigationController.navigationBar.barTintColor = IS_NightMode?[UIColor grayColor]:[UIColor whiteColor];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColor) name:kChangeNightMode object:nil];
    selectView.backgroundColor = KKColor_DarkWhite_Black;
    dataTable.backgroundColor = IS_NightMode?[UIColor colorWithHex:0x1E1E1E]:[UIColor whiteColor];
    currentIndex = 0;
    pressBtn.selected = YES;
    [self reloadClassCategroy];
    [self initUI];
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self reloadDataFromServer];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)initUI
{
    self.edgesForExtendedLayout = UIRectEdgeNone;
    dataTable.separatorStyle = UITableViewCellSeparatorStyleNone;
//    lineLab.hidden = YES;
    lineLab.userInteractionEnabled = YES;
//    [pressBtn addTarget:self action:@selector(longPressHandl:) forControlEvents:UIControlEventTouchDown];
//    [pressBtn addTarget:self action:@selector(longPressHandl2:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)reloadClassCategroy
{
    NSDictionary *params = @{};
    [WebService findChannelCategoryList:params WithBlock:^(id result, NSError *error) {
        if (!error) {
            if ([result[@"errcode"] integerValue] == 0) {
                NSArray *ary = result[@"result"][@"channelCategory"][@"value"];
                [cateList removeAllObjects];
                [cateList addObjectsFromArray:ary];
                [self setupCateView];
            }else{
                [self.view makeToast:result[@"errmsg"] position:@"center"];
            }
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败,请检查网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
    }];
}

- (void)setupCateView
{
    NSInteger i = 0;
    for (NSDictionary *item in cateList) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = (CGRect){(i+1)*pressBtn.width,0,pressBtn.size};
        [btn setTitleColor:[UIColor colorWithHex:0x46C09A] forState:UIControlStateSelected];
        [btn setTitleColor:KKColor_White_Black forState:UIControlStateNormal];
        [btn setTitle:item[@"cc_title"] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        [btn addTarget:self action:@selector(cateItemClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.tag = i + 1;
        [selectView addSubview:btn];
        i++;
    }
}

- (IBAction)pressBtnClick:(UIButton *)sender
{
    UIButton *prevBtn = [selectView viewWithTag:currentIndex];
    prevBtn.selected = NO;
    pressBtn.selected = YES;
    lineLab.center = CGPointMake(pressBtn.center.x, lineLab.center.y);
    currentIndex = 0;
    [self reloadDataFromServer];
}

- (void)cateItemClick:(UIButton *)sender
{
    if (sender.tag == currentIndex) {
        return;
    }
    UIButton *prevBtn = currentIndex == 0? pressBtn : (UIButton *)[selectView viewWithTag:currentIndex];
    prevBtn.selected = NO;
    UIButton *newBtn = [selectView viewWithTag:sender.tag];
    newBtn.selected = YES;
    lineLab.center = CGPointMake(sender.center.x, lineLab.center.y);
    
    currentIndex = sender.tag;
    [self reloadDataFromServer];
}

-(void)reloadDataFromServer
{
    NSDictionary *params;
    if (currentIndex == 0) {
        params= @{@"channel_status":@"2",@"cs_cid":[[UserEntity sharedUser] getUserID],@"currentpage":@"1",@"pagesize":@"100"};
    }else{
        NSDictionary *item = cateList[currentIndex -1];
        params= @{@"catagory_id":item[@"id"],@"cs_cid":[[UserEntity sharedUser] getUserID],@"currentpage":@"1",@"pagesize":@"100"};

    }
    [WebService findChannelList:params WithBlock:^(id result, NSError *error) {
        if (!error) {
            if ([result[@"errcode"] integerValue] == 0) {
                NSArray *ary = result[@"result"][@"channel"][@"value"];
                [dataList removeAllObjects];
                [dataList addObjectsFromArray:ary];
                [dataTable reloadData];
            }else{
                [self.view makeToast:result[@"errmsg"] position:@"center"];
            }
        }else{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败,请检查网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
    }];
}

- (void) changeColor
{
    dataTable.backgroundColor = IS_NightMode?[UIColor colorWithHex:0x1E1E1E]:[UIColor whiteColor];
    selectView.backgroundColor = KKColor_DarkWhite_Black;
    
    [dataTable reloadData];
    self.navigationController.navigationBar.barTintColor = IS_NightMode?[UIColor grayColor]:[UIColor whiteColor];
}
#pragma userAction

- (IBAction)leftSwipe:(id)sender{
    if (currentIndex == 2) {
        return;
    }
    if (currentIndex < 2) {
        UIButton *newBtn = [selectView viewWithTag:currentIndex+1];
        [self cateItemClick:newBtn];
        CATransition *animation = [CATransition animation];
        animation.duration = 0.35f;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        animation.fillMode = kCAFillModeForwards;
        animation.type = kCATransitionPush;
        animation.subtype = kCATransitionFromRight;
        [dataTable.layer addAnimation:animation forKey:@"animation"];
    }
}

- (IBAction)rightSwipe:(id)sender{
    if (currentIndex == 1) {
        [self pressBtnClick:pressBtn];
        return;
    }
    if (currentIndex > 0) {
        UIButton *newBtn = currentIndex == 1? pressBtn :(UIButton *)[selectView viewWithTag:currentIndex-1];
        [self cateItemClick:newBtn];
        CATransition *animation = [CATransition animation];
        animation.duration = 0.35f;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        animation.fillMode = kCAFillModeForwards;
        animation.type = kCATransitionPush;
        animation.subtype = kCATransitionFromLeft;
        [dataTable.layer addAnimation:animation forKey:@"animation"];
    }
}



-(void)longPressHandl:(UIButton *)sender
{
    lineLab.hidden =NO;
}

-(void)longPressHandl2:(UIButton *)sender
{
    lineLab.hidden = YES;
}

#pragma mark--DiscoverCellDelegate

-(void)sendValue:(BOOL)isSelected
{
    if (isSelected) {
        [self.view makeToast:@"                 订阅成功!\n精彩内容将呈现在首页中哦~" position:@"center"];
    } else {
        [self.view makeToast:@"已取消订阅" position:@"center"];
    }
    [self reloadDataFromServer];
}

#pragma mark --UITableViewDelegate&&UITableViewData

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return  dataList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"Dcell";
    DiscoverCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        [tableView registerNib:[UINib nibWithNibName:@"DiscoverCell" bundle:nil] forCellReuseIdentifier:identifier];
        cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    }
    cell.backgroundColor = IS_NightMode?[UIColor colorWithHex:0x1E1E1E]:[UIColor whiteColor];
    cell.nameLabel.textColor = KKColor_Black_LightGary;
    cell.rightView.backgroundColor = IS_NightMode?[UIColor colorWithHex:0x1E1E1E]:[UIColor whiteColor];
    cell.delegate = self;
    if (dataList.count > indexPath.row) {
        NSDictionary *item = dataList[indexPath.row];
        [cell setupData:item];
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [dataTable deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *item = dataList[indexPath.row];
    NSArray *subAry = item[@"is_sub"];
    BOOL isMark = subAry.count > 0;//是否已订阅
    if (isMark) {
        NewsListController *listVC = [[NewsListController alloc] init];
        listVC.dataInfo = item;
        listVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:listVC animated:YES];
    }else{
        ChannelAddViewController *addVC = [[ChannelAddViewController alloc] init];
        addVC.dataInfo = item;
        addVC.navigationController.navigationBarHidden = YES;
        addVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:addVC animated:YES];
    }
}



@end
